﻿//用到的命名空间 
using System;
using System.Web;
using System.Xml;


namespace msBsc.Cls
{ 
    //继承自IHttpModule接口 
    public class imgResourceGet : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            //context.Response.Write("Hello World");
            doHandler(context);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private void doHandler(HttpContext context)
        {
            string requestPath = context.Request.RawUrl.ToLower();
            if (!requestPath.EndsWith("img")&&!requestPath.EndsWith("img.jpg"))
            {
                return;
            }
            //context.Response.Clear();
            //context.Response.ClearHeaders();
            int itm = requestPath.LastIndexOf(' ');
            if (itm == -1)
            {
                return;
            }

            string strVfpath=requestPath.Substring(0,itm).TrimEnd();
            string strfilepath = strVfpath.Replace("/", "\\").TrimStart(new char[]{'\\',' '});
            strfilepath = CurrAppPath + strfilepath;
            System.IO.FileInfo ofinfo = new System.IO.FileInfo(strfilepath);
            if (!ofinfo.Exists)
            {
                return;
            }



            int maxWidth = 100, maxHeight = 100;
            string strtm2 = requestPath.Substring(itm).Trim().Replace("img.jpg", "").Replace("img", "");
            string[] arrstrtm1 = strtm2.Split(new char[] {'x'});
            if (arrstrtm1.Length != 2)
            {
                return;
            }
            //检查是否存在
            string strNewpath = strfilepath.Insert(strfilepath.LastIndexOf('.'), "_" + arrstrtm1[0] + "_" + arrstrtm1[1]);
            string strNewVpath = strVfpath.Insert(strVfpath.LastIndexOf('.'), "_" + arrstrtm1[0] + "_" + arrstrtm1[1]);
            if (System.IO.File.Exists(strNewpath))
            {
                context.Response.ClearContent();
                context.Response.ContentType = "image/" + ofinfo.Extension.Replace(".", "");
                context.Response.WriteFile(strNewVpath);//被替换图片  
                return;
            }

            maxWidth = int.Parse(arrstrtm1[0]);
            maxHeight = int.Parse(arrstrtm1[1]);

            using (var img = System.Drawing.Image.FromStream(ofinfo.OpenRead()))
            {
                var sourceWidth = img.Width;
                var sourceHeight = img.Height;

                var thumbWidth = sourceWidth; //要生成的缩略图的宽度
                var thumbHeight = sourceHeight; //要生成的缩略图的高度

                //计算生成图片的高度和宽度
                if (sourceWidth > maxWidth || sourceHeight > maxHeight)
                {
                    var rateWidth = (double)sourceWidth / maxWidth;
                    var rateHeight = (double)sourceHeight / maxHeight;

                    if (rateWidth > rateHeight)
                    {
                        thumbWidth = maxWidth;
                        thumbHeight = (int)Math.Round(sourceHeight / rateWidth);
                    }
                    else
                    {
                        thumbWidth = (int)Math.Round(sourceWidth / rateHeight);
                        thumbHeight = maxHeight;
                    }
                }

                using (var bmp = new System.Drawing.Bitmap(thumbWidth, thumbHeight))
                {
                    //从Bitmap创建一个System.Drawing.Graphics对象，用来绘制高质量的缩小图。
                    using (var gr = System.Drawing.Graphics.FromImage(bmp))
                    {
                        //设置 System.Drawing.Graphics对象的SmoothingMode属性为HighQuality
                        gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                        //下面这个也设成高质量
                        gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
                        //下面这个设成High
                        gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;

                        //把原始图像绘制成上面所设置宽高的缩小图
                        var rectDestination = new System.Drawing.Rectangle(0, 0, thumbWidth, thumbHeight);
                        gr.DrawImage(img, rectDestination, 0, 0, sourceWidth, sourceHeight,
                                     System.Drawing.GraphicsUnit.Pixel);

                        context.Response.ClearContent();
                        context.Response.ContentType = "image/" + ofinfo.Extension.Replace(".", "");

                        using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                        {
                            string strfextm = ofinfo.Extension.Replace(".", "").ToLower();
                            //保存图片
                            if (strfextm == "jpg")
                            {
                                try
                                {
                                    //保存图像
                                    bmp.Save(strNewpath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                }
                                catch
                                {
                                }
                                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                            else if (strfextm == "gif")
                            {
                                try
                                {
                                    //保存图像
                                    bmp.Save(strNewpath, System.Drawing.Imaging.ImageFormat.Gif);
                                }
                                catch
                                {
                                }
                                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
                            }
                            else if (strfextm == "png")
                            {
                                try
                                {
                                    //保存图像
                                    bmp.Save(strNewpath, System.Drawing.Imaging.ImageFormat.Png);
                                }
                                catch
                                {
                                }
                                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                            }
                            else if (strfextm == "bmp")
                            {
                                try
                                {
                                    //保存图像
                                    bmp.Save(strNewpath, System.Drawing.Imaging.ImageFormat.Bmp);
                                }
                                catch
                                {
                                }
                                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                            }
                            else 
                            {
                                bmp.Save(stream, System.Drawing.Imaging.ImageFormat.MemoryBmp);
                            }
                            context.Response.BinaryWrite(stream.ToArray()); 
                        }


                    }
                }
            }
              
        }


        //public string MergeResourceAndCompress(string strquery)
        //{
        //    System.Text.StringBuilder sbRet = new System.Text.StringBuilder();
        //    string[] arrstrteem = strquery.Split(',');
        //    int icount = arrstrteem.Length;
        //    for (int i = 0; i < arrstrteem.Length; i++)
        //    {
        //        string strfilepath = arrstrteem[i];
        //        //if (strfilepath.StartsWith("j_"))
        //        //{
        //        strfilepath = CurrAppPath + "jqPlugin\\" + strfilepath.Replace("/", "\\");
        //        //}
        //        msBsc.AppLogic.Cfg.JSCompress oJSCompress = new AppLogic.Cfg.JSCompress();
        //        sbRet.AppendLine(oJSCompress.doCompressFromFile(strfilepath));
        //    }

        //    return sbRet.ToString();
        //}


        private string _CurrAppPath = "";
        /// <summary>
        /// 程序主目录,WEB站点目录，以\\结尾
        /// </summary>
        public string CurrAppPath
        {
            get
            {
                if (_CurrAppPath == string.Empty)
                {
                    if (HttpContext.Current == null)
                    {
                        _CurrAppPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
                    }
                    else
                    {
                        _CurrAppPath = HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath);
                    }
                    if (!_CurrAppPath.EndsWith("\\"))
                    {
                        _CurrAppPath = _CurrAppPath + "\\";
                    }
                }
                return _CurrAppPath;
            }
        }



    }
}